#include "downloadunits.h"
#include "downloadlistitemwidget.h"
#include "downloadthreadmanager.h"
#include <QDebug>

DownloadUnits::DownloadUnits(const QString& url, QWidget *parent )
    : m_url(url)
{
    m_downloadItem = new DownloadListItemWidget(parent);
    m_downloadThread = new DownloadThreadManager(parent);
    connect(m_downloadThread,SIGNAL(progressChange(qint64,qint64)),
            m_downloadItem,SLOT(progressChangeSlot(qint64,qint64)));
    connect(m_downloadThread,SIGNAL(updateFileInfo(QString,qint64)),
            m_downloadItem,SLOT(updateFileInfo(QString,qint64)));
    connect(m_downloadThread,SIGNAL(stateChanged(QString)),
            m_downloadItem,SLOT(stateChanged(QString)));
    connect(m_downloadThread,SIGNAL(downloadingFinished()),
                             SLOT(downloadingFinished()));
    connect(this,SIGNAL(removeItemWidget(QString)),
            parent,SLOT(downloadingFinished(QString)));

    m_pause = false;
}

DownloadUnits::~DownloadUnits()
{
    pause();
    m_downloadItem;
    m_downloadThread;
}

DownloadListItemWidget* DownloadUnits::getDownloadItemWidget()
{
    return m_downloadItem;
}

void DownloadUnits::pause()
{
    m_pause = true;
    m_downloadThread->pause();
}

void DownloadUnits::start()
{
    if(!m_pause)
        m_downloadThread->downloadFile(m_url);
    else
        m_downloadThread->restart();
}

int DownloadUnits::getState() const
{
    return m_downloadThread->getState();
}

void DownloadUnits::setStateChanged(const QString& state)
{
    m_downloadItem->stateChanged(state);
}

void DownloadUnits::errorCode(QString errorString)
{
    qDebug()<<errorString;
}

void DownloadUnits::downloadingFinished()
{
    emit removeItemWidget(m_url);
}
